<template>
  <div class="publish-container">
    <div class="publish-header">
      <h1>发布商品</h1>
      <p>轻松出售你的闲置物品，让资源得到充分利用</p>
      
      <!-- 步骤条 -->
      <div class="steps-container">
        <el-steps :active="currentStep - 1" space="40" align-center>
          <el-step title="基本信息" description="填写商品标题、分类等" />
          <el-step title="详细描述" description="添加图片和详细说明" />
          <el-step title="交易信息" description="选择交易方式和联系方式" />
        </el-steps>
      </div>
    </div>
    
    <!-- 步骤1：基本信息 -->
    <div v-if="currentStep === 1" class="publish-step">
      <el-form 
        :model="productForm" 
        :rules="rules" 
        ref="productFormRef"
        label-width="100px"
        class="publish-form"
      >
        <el-form-item label="商品标题" prop="title">
          <el-input 
            v-model="productForm.title" 
            placeholder="请输入商品标题（2-50个字符）" 
            maxlength="50"
            show-word-limit
            clearable
            :validate-event="false"
          />
        </el-form-item>
        
        <el-form-item label="商品分类" prop="categoryId">
          <el-select 
            v-model="productForm.categoryId" 
            placeholder="请选择商品分类"
            style="width: 100%"
            clearable
            :validate-event="false"
          >
            <el-option 
              v-for="category in categories" 
              :key="category.id" 
              :label="category.name" 
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="商品价格" prop="price">
          <el-input-number 
            v-model="productForm.price" 
            :min="0.01" 
            :step="0.01" 
            :precision="2"
            placeholder="请输入价格"
            style="width: 100%"
            :validate-event="false"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="nextStep">下一步</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="cancelPublish">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 步骤2：详细描述 -->
    <div v-if="currentStep === 2" class="publish-step">
      <el-form 
        :model="productForm" 
        :rules="rules" 
        ref="productFormRef"
        label-width="100px"
        class="publish-form"
      >
        <el-form-item label="新旧程度" prop="condition">
          <el-rate 
            v-model="productForm.condition" 
            :max="5" 
            show-score 
            text-color="#67C23A"
            score-template="{value}成新"
            :validate-event="false"
          />
        </el-form-item>
        
        <el-form-item label="商品描述" prop="description">
          <el-input 
            v-model="productForm.description" 
            type="textarea" 
            :rows="5" 
            placeholder="请详细描述商品的使用情况、购买时间、有无瑕疵等信息"
            maxlength="1000"
            show-word-limit
            :validate-event="false"
          />
        </el-form-item>
        
        <el-form-item label="商品图片" prop="images">
          <el-upload
            v-model:file-list="fileList"
            multiple
            action="#"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            accept="image/*"
            :validate-event="false"
          >
            <el-icon><i-ep-plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                请上传商品图片（最多9张，支持jpg/png格式）
              </div>
            </template>
          </el-upload>
          <el-dialog v-model="dialogVisible" title="图片预览" width="80%">
            <img :src="dialogImageUrl" alt="预览图片" style="width: 100%">
          </el-dialog>
        </el-form-item>
        
        <el-form-item>
          <el-button @click="prevStep">上一步</el-button>
          <el-button type="primary" @click="nextStep">下一步</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 步骤3：交易信息 -->
    <div v-if="currentStep === 3" class="publish-step">
      <el-form 
        :model="productForm" 
        :rules="rules" 
        ref="productFormRef"
        label-width="100px"
        class="publish-form"
      >
        <el-form-item label="交易方式" prop="tradeType">
          <el-checkbox-group v-model="productForm.tradeType" :validate-event="false">
            <el-checkbox label="线下交易" border>线下交易</el-checkbox>
            <el-checkbox label="校内配送" border>校内配送</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input 
            v-model="productForm.contactPhone" 
            placeholder="请输入联系电话"
            clearable
            :validate-event="false"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button @click="prevStep">上一步</el-button>
          <el-button type="primary" @click="submitForm">发布商品</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 发布须知 (所有步骤都显示) -->
    <div class="publish-tips">
      <h3>发布须知</h3>
      <ul>
        <li>请确保商品信息真实有效，不得发布违规商品</li>
        <li>建议上传清晰、多角度的商品图片，提高交易成功率</li>
        <li>商品价格建议参考市场行情，避免过高或过低</li>
        <li>交易过程中请保持沟通畅通，诚信交易</li>
        <li>如遇纠纷，请及时联系平台客服</li>
      </ul>
    </div>
    
    <!-- 发布成功对话框 -->
    <el-dialog
      v-model="successDialogVisible"
      title="发布成功"
      :show-close="false"
      width="30%"
    >
      <div class="success-content">
        <el-icon class="success-icon"><i-ep-success-filled /></el-icon>
        <p>商品发布成功！</p>
        <p class="success-tip">请耐心等待审核通过</p>
      </div>
      <template #footer>
        <el-button type="primary" @click="goToHome">返回首页</el-button>
        <el-button @click="publishAnother">发布另一个</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const productFormRef = ref()
const dialogVisible = ref(false)
const dialogImageUrl = ref('')
const fileList = ref([])
const currentStep = ref(1)
const successDialogVisible = ref(false)

// 商品表单数据
const productForm = reactive({
  title: '',
  categoryId: '',
  price: '',
  condition: 5,
  description: '',
  images: [],
  tradeType: ['线下交易'], // 默认选择线下交易
  contactPhone: ''
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入商品标题', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度在 2 到 50 个字符之间', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' }
  ],
  condition: [
    { required: true, message: '请选择新旧程度', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入商品描述', trigger: 'blur' },
    { min: 10, message: '描述至少10个字符', trigger: 'blur' }
  ],
  tradeType: [
    { required: true, message: '请选择交易方式', trigger: 'change' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ]
}

// 商品分类数据
const categories = ref([
  { id: 1, name: '数码产品' },
  { id: 2, name: '图书文具' },
  { id: 3, name: '服装鞋包' },
  { id: 4, name: '生活用品' },
  { id: 5, name: '运动器材' },
  { id: 6, name: '其他' }
])

// 图片预览
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

// 移除图片
const handleRemove = (file) => {
  const index = fileList.value.indexOf(file)
  if (index > -1) {
    fileList.value.splice(index, 1)
  }
}

// 图片上传前校验
const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('只支持JPG/PNG格式!')
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
  }
  if (fileList.value.length >= 9) {
    ElMessage.error('最多只能上传9张图片!')
    return false
  }
  return isJPG && isLt2M
}

// 下一步
const nextStep = () => {
  // 根据当前步骤验证表单
  let isValid = true
  
  if (currentStep.value === 1) {
    productFormRef.value.validateField(['title', 'categoryId', 'price'], (errors) => {
      if (errors) {
        isValid = false
        ElMessage.error('请完善基本信息')
      }
    })
  } else if (currentStep.value === 2) {
    productFormRef.value.validateField(['description'], (errors) => {
      if (errors) {
        isValid = false
        ElMessage.error('请填写商品描述')
      }
    })
    if (fileList.value.length === 0) {
      isValid = false
      ElMessage.warning('建议至少上传一张商品图片')
    }
  }
  
  if (isValid) {
    currentStep.value++
    // 滚动到顶部
    window.scrollTo({ top: 0, behavior: 'smooth' })
  }
}

// 上一步
const prevStep = () => {
  if (currentStep.value > 1) {
    currentStep.value--
    window.scrollTo({ top: 0, behavior: 'smooth' })
  }
}

// 提交表单
const submitForm = () => {
  productFormRef.value.validateField(['tradeType', 'contactPhone'], (errors) => {
    if (errors) {
      ElMessage.error('请完善交易信息')
      return
    }
    
    // 模拟提交到服务器
    ElMessageBox.confirm('确定要发布该商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      // 这里应该调用API发布商品
      ElMessage.success('正在提交商品信息...')
      
      // 模拟提交延迟
      setTimeout(() => {
        successDialogVisible.value = true
      }, 1500)
    }).catch(() => {
      ElMessage.info('已取消发布')
    })
  })
}

// 返回首页
const goToHome = () => {
  successDialogVisible.value = false
  router.push('/')
}

// 发布另一个
const publishAnother = () => {
  successDialogVisible.value = false
  resetForm()
  currentStep.value = 1
}

// 重置表单
const resetForm = () => {
  if (productFormRef.value) {
    productFormRef.value.resetFields()
  }
  fileList.value = []
  productForm.tradeType = ['线下交易'] // 重置默认值
  
  // 清理图片URL对象
  fileList.value.forEach(file => {
    if (file.url && file.url.startsWith('blob:')) {
      URL.revokeObjectURL(file.url)
    }
  })
}

// 取消发布
const cancelPublish = () => {
  router.go(-1)
}

// 页面加载时检查登录状态
onMounted(() => {
  // 这里应该检查用户是否已登录
  // 如果未登录，跳转到登录页面
  // 模拟已登录状态
  // const isLoggedIn = checkLoginStatus()
  // if (!isLoggedIn) {
  //   router.push('/login')
  // }
})
</script>

<style scoped>
.publish-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 20px;
}

.publish-header {
  text-align: center;
  margin-bottom: 40px;
}

.steps-container {
  margin-top: 30px;
  max-width: 800px;
  margin-left: auto;
  margin-right: auto;
}

.publish-step {
  animation: slideIn 0.5s ease-out;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.publish-header h1 {
  font-size: 36px;
  color: #333;
  margin-bottom: 10px;
  position: relative;
  display: inline-block;
}

.publish-header h1::after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  width: 80px;
  height: 4px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 2px;
}

.publish-header p {
  font-size: 18px;
  color: #666;
  margin-top: 20px;
}

.publish-form {
  background: white;
  padding: 40px;
  border-radius: 16px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
  margin-bottom: 40px;
}

.publish-tips {
  background: #f8f9ff;
  padding: 30px;
  border-radius: 12px;
  border-left: 4px solid #667eea;
}

.publish-tips h3 {
  font-size: 20px;
  color: #333;
  margin-bottom: 20px;
}

.publish-tips ul {
  padding-left: 20px;
  color: #666;
  line-height: 1.8;
}

.publish-tips li {
  margin-bottom: 10px;
  position: relative;
}

.publish-tips li::before {
  content: '•';
  color: #667eea;
  font-weight: bold;
  margin-right: 10px;
}

/* 发布成功样式 */
.success-content {
  text-align: center;
  padding: 20px 0;
}

.success-icon {
  font-size: 60px;
  color: #67c23a;
  margin-bottom: 20px;
}

.success-content p {
  margin: 10px 0;
  color: #303133;
}

.success-tip {
  color: #909399 !important;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .publish-container {
    padding: 20px;
  }
  
  .publish-form {
    padding: 20px;
  }
  
  .publish-header h1 {
    font-size: 28px;
  }
  
  .steps-container {
    margin-top: 20px;
  }
  
  .el-steps {
    --el-steps-process-text-color: #409eff;
    --el-steps-process-border-color: #409eff;
    --el-steps-process-background-color: #409eff;
  }
  
  .el-checkbox-group {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
}
</style>
